package vn.co.thn.android.videohot.activity;


import vn.co.thn.android.videohot.R;
import vn.co.thn.android.videohot.VHConstants;
import vn.co.thn.android.videohot.common.VHCommonActivity;
import vn.co.thn.android.videohot.data.VHVideoItemData;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.facebook.AppEventsLogger;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.LoginButton;

public class VHAuthFacebookActivity extends VHCommonActivity {
	private static final String PERMISSION = "publish_actions";
	private GraphUser user;
	private VHVideoItemData video;
	private LoginButton loginButton;
	private UiLifecycleHelper uiHelper;
	private final String PENDING_ACTION_BUNDLE_KEY = "vn.co.thn.android.videohot.activity:PendingAction";
	private boolean canPresentShareDialog;
	private PendingAction pendingAction = PendingAction.NONE;
	private boolean showlogin = false;

	private enum PendingAction {
		NONE, POST_PHOTO, POST_STATUS_UPDATE
	}

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state, Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};
	private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
		@Override
		public void onError(FacebookDialog.PendingCall pendingCall, Exception error, Bundle data) {
			Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
			video = null;
			finish();
		}

		@Override
		public void onComplete(FacebookDialog.PendingCall pendingCall, Bundle data) {
			Log.d("HelloFacebook", "Success!");
			video = null;
			finish();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(this, callback);
		uiHelper.onCreate(savedInstanceState);

		if (savedInstanceState != null) {
			String name = savedInstanceState.getString(PENDING_ACTION_BUNDLE_KEY);
			pendingAction = PendingAction.valueOf(name);
		}
		setContentView(R.layout.vh_auth_facebook_activity);
		video = (VHVideoItemData) getIntent().getSerializableExtra(VHConstants.EXTRA_VIDEO);

		loginButton = (LoginButton) findViewById(R.id.login_button);
		loginButton.setVisibility(View.GONE);
		loginButton.setUserInfoChangedCallback(new LoginButton.UserInfoChangedCallback() {
			@Override
			public void onUserInfoFetched(GraphUser user) {
				VHAuthFacebookActivity.this.user = user;
				if (user != null && !showlogin) {
					loginButton.setVisibility(View.GONE);
					performPublish(PendingAction.POST_STATUS_UPDATE, canPresentShareDialog);
				} else {
					handlePendingAction();
				}
			}
		});
		canPresentShareDialog = FacebookDialog.canPresentShareDialog(this, FacebookDialog.ShareDialogFeature.SHARE_DIALOG);

	}

	@Override
	protected void onResume() {
		super.onResume();
		uiHelper.onResume();
		AppEventsLogger.activateApp(this);

	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
		outState.putString(PENDING_ACTION_BUNDLE_KEY, pendingAction.name());
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data, dialogCallback);
	}

	@Override
	public void onPause() {
		super.onPause();
		uiHelper.onPause();
		AppEventsLogger.deactivateApp(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	private void onSessionStateChange(Session session, SessionState state, Exception exception) {
		if (pendingAction != PendingAction.NONE
				&& (exception instanceof FacebookOperationCanceledException || exception instanceof FacebookAuthorizationException)) {
			new AlertDialog.Builder(VHAuthFacebookActivity.this).setTitle("cancelled")
					.setMessage("Unable to perform selected action because permissions were not granted.").setPositiveButton("OK", null).show();
			pendingAction = PendingAction.NONE;
			finish();
		} else if (state == SessionState.OPENED_TOKEN_UPDATED) {
			handlePendingAction();
		}
	}

	@SuppressWarnings("incomplete-switch")
	private void handlePendingAction() {
		PendingAction previouslyPendingAction = pendingAction;
		// These actions may re-set pendingAction if they are still pending, but
		// we assume they
		// will succeed.
		pendingAction = PendingAction.NONE;

		switch (previouslyPendingAction) {
		case POST_PHOTO:
			// postPhoto();
			break;
		case POST_STATUS_UPDATE:
			// postStatusUpdate();
			PostStatus();
			break;
		}
		if (user == null && !showlogin) {
			showlogin = true;
			pendingAction = PendingAction.POST_STATUS_UPDATE;
			loginButton.performClick();

		}
	}

	private boolean hasPublishPermission() {
		Session session = Session.getActiveSession();
		return session != null && session.getPermissions().contains("publish_actions");
	}

	private void performPublish(PendingAction action, boolean allowNoSession) {
		Session session = Session.getActiveSession();
		if (session != null) {
			pendingAction = action;
			if (hasPublishPermission()) {
				// We can do the action right away.
				handlePendingAction();
				return;
			} else if (session.isOpened()) {
				// We need to get new permissions, then complete the action when
				// we get called back.
				session.requestNewPublishPermissions(new Session.NewPermissionsRequest(this, PERMISSION));
				return;
			}
		}

		if (allowNoSession) {
			pendingAction = action;
			handlePendingAction();
		}
	}

	private FacebookDialog.ShareDialogBuilder createShareDialogBuilderForLink() {
		return new FacebookDialog.ShareDialogBuilder(this).setName(video.getTitle()).setDescription(video.getContent().getValue())
				.setPicture(video.getImage_Url()).setLink("http://video-hot.appspot.com/play/v/" + video.getEmbed_code());
	}

	// private void showPublishResult(String message, GraphObject result,
	// FacebookRequestError error) {
	// String title = null;
	// String alertMessage = null;
	// if (error == null) {
	// title = getString(R.string.success);
	// String id = result.cast(GraphObjectWithId.class).getId();
	// alertMessage = getString(R.string.successfully_posted_post, message, id);
	// } else {
	// title = getString(R.string.error);
	// alertMessage = error.getErrorMessage();
	// }
	//
	// new AlertDialog.Builder(this)
	// .setTitle(title)
	// .setMessage(alertMessage)
	// .setPositiveButton(R.string.ok, null)
	// .show();
	// }
	private void PostStatus() {
		// isPermission = true;

		if (canPresentShareDialog) {
			FacebookDialog shareDialog = createShareDialogBuilderForLink().build();
			uiHelper.trackPendingDialogCall(shareDialog.present());
		} else if (user != null && hasPublishPermission()) {
			// final String message = "Post complete";
			// Request request = Request
			// .newStatusUpdateRequest(Session.getActiveSession(), message,
			// place, tags, new Request.Callback() {
			// @Override
			// public void onCompleted(Response response) {
			// showPublishResult(message, response.getGraphObject(),
			// response.getError());
			// }
			// });
			// request.executeAsync();
			//
			Bundle params = new Bundle();
			params.putString("message", video.getTitle());
			params.putString("description", video.getContent().getValue());
			params.putString("picture", video.getImage_Url());
			params.putString("link", "http://video-hot.appspot.com/play/v/" + video.getEmbed_code());
			Request request = new Request(Session.getActiveSession(), "me/feed", params, HttpMethod.POST);
			request.setCallback(new Request.Callback() {
				@Override
				public void onCompleted(Response response) {
					if (response.getError() == null) {
						// success!
						Toast.makeText(getApplicationContext(), "post complete", Toast.LENGTH_LONG).show();
						finish();

					} else {
						// not success!
						Toast.makeText(getApplicationContext(), "post Fail", Toast.LENGTH_LONG).show();
					}
					video = null;
				}
			});
			request.executeAsync();
		} else {
			pendingAction = PendingAction.POST_STATUS_UPDATE;
		}

	}

}
